package controllers

import (
	"fmt"
	"gin-mvc/pkg/exceptions"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type (
	BaseController struct {
		Ctx *gin.Context
	}
)

func (ctl *BaseController) ParamsError(errMsg string) {
	ctl.Error(exceptions.InvalidParams, errMsg)
	return
}

func (ctl *BaseController) Error(code int, errMsg ...string) {
	ctl.Ctx.JSON(http.StatusOK, exceptions.NewCodeError(code, checkMessage(code, errMsg)))
	return
}

func (ctl *BaseController) SendJson(code int, data interface{}, messages ...string) {
	ctl.Ctx.JSON(http.StatusOK, gin.H{
		"code":    code,
		"message": checkMessage(code, messages),
		"data":    data,
	})
	return
}

func checkMessage(code int, messages interface{}) string {
	var message string
	messagesArr := messages.([]string)
	if message = exceptions.GetMsg(code); message == "" {
		if len(messagesArr) != 1 {
			log.Fatalf("请设置`message`， code：%v\n", code)
		}
	}
	if len(messagesArr) > 0 {
		fmt.Println(messagesArr)
		message = messagesArr[0]
	}

	return message
}
